var API = require('../../utils/api/index.js')
Page({
  data: {
    scrollHeight: 0,
    imgUrls: [],
    menuTypeList: [],
    menuInfoList: [],
    activeIndex: '',
    allPosArray: [],
    allPosArraybottom: [],
    toView: '',
    contentHight: 0,
    shoppingList: [],
    totalCount: 0,
    totalPrice: 0,
    clearVisible: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that  = this
    let imgUrls = []
    API.ajax('', function (res) {
      for (var i = 0; i < res.data.length; i++) {
        imgUrls.push(res.data[i].img)
      }

      that.setData({
        imgUrls: imgUrls
      })
    })
    wx.getSystemInfo({
      success: function (res) {
        // 高度,宽度 单位为px
        that.setData({
          scrollHeight:  res.windowHeight - 200 - 50
        })
      }
    })

    API.menuAjax('', function (res) {
      let data = res.data
      let menuAarry = []
      for (let x = 0; x < data.length; x++){
        var findIndex = menuAarry.findIndex((value, index, arr) => {
          return value.type == data[x].type.type
        })
        if (findIndex == undefined || findIndex == -1){
          var obj = {
            type: data[x].type.type,
            msg: data[x].type.msg,
            data: []
          }
          menuAarry.push(obj)
        }else{
          menuAarry[findIndex].data.push(data[x])
        } 
        
      }
      that.setData({
        menuInfoList: res.data,
        menuTypeList: menuAarry,
        activeIndex: 'menu0',
        toView: 'menu0'
      })
    })
    this.queryMultipleNodes()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },
  changeIndex: function (e){
    var index = e.target.dataset.index
    const that = this

    this.setData({
      activeIndex: 'menu' + index,
      toView: 'menu' + index
    })
  },
  queryMultipleNodes: function () {
    var that = this;
    let query = wx.createSelectorQuery().in(this)
    var aboutArr = [];
    var bottomArr= [];
    let data = this.data.menuTypeList
    let s = 0
    let wHeight = 0
    for (var y = 0; y < data.length;y++){
      query.selectAll(`#menu${y}`).boundingClientRect(function (rects) {
        rects.forEach(function (rect) {
          s += rect.height
          s = s - 38
          aboutArr.push(s);
        })
      })
    }
    //计算容器高度
    query.select('.content').boundingClientRect(function (res) {
        wHeight = res.height
    }).exec(); 
    that.setData({
      allPosArray: aboutArr,
      contentHight: wHeight
    })
  },
  monitorScroll: function (e){
    let scrollTop = e.detail.scrollTop // 滚动距离
    let srcollArr = this.data.allPosArray
    // 滚动距离> 未显示剩余高度
    if (scrollTop >= srcollArr[srcollArr.length - 1] - this.data.contentHight){
      return
    }
    else{
      for(var x= 0;x< srcollArr.length;x++){
        if(scrollTop >= 0 && scrollTop < srcollArr[0]){
          this.setData({
            toView: 'menu0'
          })
          return false
        }
        // 上一个类高度 <= 滚动距离 < 当前类的高度
        else if (scrollTop >= srcollArr[x - 1] && scrollTop  < srcollArr[x]){
          this.setData({
            toView: 'menu' + x
          })
          return false
        }
      }
    }
  },
  addCart: function (e){
    var id = e.currentTarget.dataset.id
    var item = this.data.menuInfoList.find((itx) => id == itx.id)
    item['count'] = 1;
    item['totalPrice'] = (item.price * item.count).toFixed(2)
    let list = this.data.shoppingList
    list.push(item)
    this.setData({
      shoppingList: list
    })
    this.bindSummary()
  },
  // 汇总
  bindSummary: function(e){
    let shopList = this.data.shoppingList
    let total = 0
    let p_total = 0
    shopList.forEach((ele, index) => {
      total = total + ele.count
      p_total = (parseInt(p_total) + ele.price * ele.count).toFixed(2)
    })
    this.setData({
      totalCount: total,
      totalPrice: p_total
    })
  },
  // 显示弹出框
  showModule: function(){
    if (this.data.shoppingList.length > 0){
      this.selectComponent('#self-bottom-pop').toggleMoal()
    }
  },
  // 减少数量
  handDelCount: function (e) {
    let id = e.currentTarget.dataset.id
    let list = this.data.shoppingList
    list.forEach((ele, index) => {
      if(ele.id === id){
        if (ele.count > 1) {
          ele.count--;
          ele.totalPrice = (ele.price * ele.count).toFixed(2)
        }
        return
      }
    })
    this.setData({
      shoppingList: list
    })
    this.bindSummary()
  },
  // 增加数量
  handAddCount: function (e) {
    let id = e.currentTarget.dataset.id
    let list = this.data.shoppingList
    list.forEach((ele, index) => {
      if (ele.id === id) {
        ele.count++;
        ele.totalPrice = (ele.price * ele.count).toFixed(2)
        return
      }
    })
    this.setData({
      shoppingList: list
    })
    this.bindSummary()
  },
  
  // 清空购物车
  handClearList: function(e){
    this.setData({
      clearVisible: false,
      shoppingList: [],
      totalCount: 0,
      totalPrice: 0
    })
    this.selectComponent('#self-bottom-pop').toggleMoal()
  },
  toggleClearbtn: function(){
    const that = this
    let value = !that.data.clearVisible
    this.setData({
      clearVisible: value,
    })
  },
  // 提交数据
  submitData: function(){
    if(this.data.shoppingList.length > 0){
      wx.navigateTo({
        url: '../shoppingCart/index'
      })
    }
  }
})